// 屏幕坐标与设备分辨率映射工具
export default class Position {
  constructor(displayElement, deviceWidth, deviceHeight) {
    this.displayElement = displayElement
    this.deviceWidth = deviceWidth || 720
    this.deviceHeight = deviceHeight || 1280
  }

  setDeviceSize(width, height) {
    if (width > 0 && height > 0) {
      this.deviceWidth = width >>> 0
      this.deviceHeight = height >>> 0
    }
  }

  // 将 PointerEvent 坐标转换为设备坐标（整型并裁剪到范围内）
  toDevicePoint(clientX, clientY) {
    const el = this.displayElement
    const rect = el.getBoundingClientRect()
    const baseW = this.deviceWidth || el.width || el.offsetWidth || 1
    const baseH = this.deviceHeight || el.height || el.offsetHeight || 1
    const scaleX = (el.offsetWidth || rect.width || 1) / baseW
    const scaleY = (el.offsetHeight || rect.height || 1) / baseH
    const x = Math.round((clientX - rect.left) / (scaleX || 1))
    const y = Math.round((clientY - rect.top) / (scaleY || 1))
    const clampedX = Math.max(0, Math.min(this.deviceWidth - 1, x)) >>> 0
    const clampedY = Math.max(0, Math.min(this.deviceHeight - 1, y)) >>> 0
    return { x: clampedX, y: clampedY }
  }
}


